package cn.example.practice.db;

import cn.example.practice.model.CartItem;
import cn.example.practice.util.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ShopCartDao {
    private static final Logger LOGGER = Logger.getLogger(ShopCartDao.class.getName());

    private static final String INSERT_CART_ITEM =
            "INSERT INTO shop_cart (user_id, goods_id, quantity) VALUES (?, ?, ?)";
    private static final String UPDATE_CART_ITEM =
            "UPDATE shop_cart SET quantity = ? WHERE user_id = ? AND goods_id = ?";
    private static final String DELETE_CART_ITEM =
            "DELETE FROM shop_cart WHERE user_id = ? AND goods_id = ?";
    private static final String SELECT_CART_ITEMS =
            "SELECT c.id, c.quantity, g.id as goods_id, g.name, g.price, g.image_data, g.image_type " +
                    "FROM shop_cart c " +
                    "JOIN goods g ON c.goods_id = g.id " +
                    "WHERE c.user_id = ?";
    private static final String SELECT_CART_ITEM =
            "SELECT id, quantity FROM shop_cart WHERE user_id = ? AND goods_id = ?";

    public boolean addToCart(Long userId, Long goodsId, int quantity) {
        try {
            // 检查商品是否已在购物车中
            try (ResultSet rs = JDBCUtils.executeQuery(SELECT_CART_ITEM, userId, goodsId)) {
                if (rs.next()) {
                    // 更新数量
                    int newQuantity = rs.getInt("quantity") + quantity;
                    return JDBCUtils.executeUpdate(UPDATE_CART_ITEM, newQuantity, userId, goodsId) > 0;
                } else {
                    // 添加新商品
                    return JDBCUtils.executeUpdate(INSERT_CART_ITEM, userId, goodsId, quantity) > 0;
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error adding item to cart: " + goodsId, e);
            return false;
        }
    }

    public boolean updateQuantity(Long userId, Long goodsId, int quantity) {
        try {
            if (quantity <= 0) {
                return removeFromCart(userId, goodsId);
            }
            return JDBCUtils.executeUpdate(UPDATE_CART_ITEM, quantity, userId, goodsId) > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error updating cart item quantity: " + goodsId, e);
            return false;
        }
    }

    public boolean removeFromCart(Long userId, Long goodsId) {
        try {
            return JDBCUtils.executeUpdate(DELETE_CART_ITEM, userId, goodsId) > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error removing item from cart: " + goodsId, e);
            return false;
        }
    }

    public List<CartItem> getCartItems(Long userId) {
        List<CartItem> items = new ArrayList<>();
        try (ResultSet rs = JDBCUtils.executeQuery(SELECT_CART_ITEMS, userId)) {
            while (rs.next()) {
                items.add(new CartItem(
                        rs.getLong("id"),
                        rs.getLong("goods_id"),
                        rs.getString("name"),
                        rs.getFloat("price"),
                        rs.getInt("quantity"),
                        rs.getString("image_data"),
                        rs.getString("image_type")
                ));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "Error retrieving cart items for user: " + userId, e);
        }
        return items;
    }
}
